package com.aihna.web.service.impl;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import cn.binarywang.wx.miniapp.bean.WxMaPhoneNumberInfo;
import cn.dev33.satoken.secure.BCrypt;
import cn.dev33.satoken.stp.SaLoginModel;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.util.ObjectUtil;
import com.aihna.common.core.exception.user.UserException;
import com.aihna.common.satoken.utils.LoginHelper;
import com.aihna.mall.domain.bo.StoreUserBo;
import com.aihna.mall.domain.vo.StoreUserVo;
import com.aihna.mall.service.IStoreUserService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import com.aihna.common.core.domain.model.XcxLoginBody;
import com.aihna.common.core.domain.model.XcxLoginUser;
import com.aihna.common.core.enums.UserStatus;
import com.aihna.common.core.utils.ValidatorUtils;
import com.aihna.common.json.utils.JsonUtils;
import com.aihna.system.domain.SysClient;
import com.aihna.system.domain.vo.SysUserVo;
import com.aihna.web.domain.vo.LoginVo;
import com.aihna.web.service.IAuthStrategy;
import com.aihna.web.service.SysLoginService;
import me.chanjar.weixin.common.error.WxErrorException;
import org.springframework.stereotype.Service;

/**
 * 邮件认证策略
 *
 * @author Michelle.Chung
 */
@Slf4j
@Service("xcx" + IAuthStrategy.BASE_NAME)
@RequiredArgsConstructor
public class XcxAuthStrategy implements IAuthStrategy {

    private final WxMaService wxMaService;

    private final IStoreUserService storeUserService;

    @Override
    public LoginVo login(String body, SysClient client) {
        String openid = "";

        XcxLoginBody loginBody = JsonUtils.parseObject(body, XcxLoginBody.class);
        ValidatorUtils.validate(loginBody);
        // xcxCode 为 小程序调用 wx.login 授权后获取
        String xcxCode = loginBody.getXcxCode();
        // 多个小程序识别使用
        String appid = loginBody.getAppid();
        String encryptedData = loginBody.getEncryptedData();
        String iv = loginBody.getIv();

        if (!wxMaService.switchover(appid)) {
            throw new IllegalArgumentException(String.format("未找到对应appid=[%s]的配置，请核实！", appid));
        }

        //切换小程序，管理多个小程序
        wxMaService.switchoverTo(appid);
        WxMaPhoneNumberInfo phoneNoInfo;
        try {
            WxMaJscode2SessionResult session = wxMaService.getUserService().getSessionInfo(xcxCode);
            openid = session.getOpenid();
            phoneNoInfo = wxMaService.getUserService().getPhoneNoInfo(session.getSessionKey(), encryptedData, iv);
        } catch (WxErrorException e) {
            throw new RuntimeException(e);
        }


        // 框架登录不限制从什么表查询 只要最终构建出 LoginUser 即可
        StoreUserVo user = loadUserByPhone(phoneNoInfo.getPhoneNumber());
        // 此处可根据登录用户的数据不同 自行创建 loginUser 属性不够用继承扩展就行了
        XcxLoginUser loginUser = new XcxLoginUser();
        loginUser.setTenantId(user.getTenantId());
        loginUser.setUserId(user.getId());
        loginUser.setUsername(user.getUsername());
        loginUser.setNickname(user.getNickname());
        loginUser.setUserType(user.getLoginType());
        loginUser.setClientKey(client.getClientKey());
        loginUser.setDeviceType(client.getDeviceType());
        loginUser.setPhone(user.getPhone());
        loginUser.setOpenid(openid);

        SaLoginModel model = new SaLoginModel();
        model.setDevice(client.getDeviceType());
        // 自定义分配 不同用户体系 不同 token 授权时间 不设置默认走全局 yml 配置
        // 例如: 后台用户30分钟过期 app用户1天过期
        model.setTimeout(client.getTimeout());
        model.setActiveTimeout(client.getActiveTimeout());
        model.setExtra(LoginHelper.CLIENT_KEY, client.getClientId());
        // 生成token
        LoginHelper.login(loginUser, model);

        LoginVo loginVo = new LoginVo();
        loginVo.setAccessToken(StpUtil.getTokenValue());
        loginVo.setExpireIn(StpUtil.getTokenTimeout());
        loginVo.setClientId(client.getClientId());
        loginVo.setOpenid(openid);
        return loginVo;
    }

    private StoreUserVo loadUserByPhone(String phoneNumber) {
        // 使用 openid 查询绑定用户 如未绑定用户 则根据业务自行处理 例如 创建默认用户
        StoreUserVo storeUserVo = storeUserService.selectUserByPhone(phoneNumber);
        if (ObjectUtil.isNull(storeUserVo)) {
            log.info("登录用户：{} 不存在.", phoneNumber);
            StoreUserBo storeUserBo = new StoreUserBo();
            storeUserBo.setUsername(phoneNumber);
            storeUserBo.setNickname(phoneNumber);
            storeUserBo.setPhone(phoneNumber);
            storeUserBo.setPassword(BCrypt.hashpw("123456"));
            storeUserBo.setUserType("routime");
            storeUserService.insertByBo(storeUserBo);

            storeUserVo = new StoreUserVo();
            storeUserVo.setId(storeUserBo.getId());
            storeUserVo.setUsername(phoneNumber);
            storeUserVo.setNickname(phoneNumber);
            storeUserVo.setPhone(phoneNumber);
            storeUserVo.setLoginType(storeUserBo.getUserType());
        } else if (storeUserVo.getStatus().equals("0")) {
            log.info("登录用户：{} 已被停用.", phoneNumber);
            throw new UserException("user.blocked", "");
        }
        return storeUserVo;
    }

    private SysUserVo loadUserByOpenid(String openid) {
        // 使用 openid 查询绑定用户 如未绑定用户 则根据业务自行处理 例如 创建默认用户
        // todo 自行实现 userService.selectUserByOpenid(openid);
        SysUserVo user = new SysUserVo();
        if (ObjectUtil.isNull(user)) {
            log.info("登录用户：{} 不存在.", openid);
            // todo 用户不存在 业务逻辑自行实现
        } else if (UserStatus.DISABLE.getCode().equals(user.getStatus())) {
            log.info("登录用户：{} 已被停用.", openid);
            // todo 用户已被停用 业务逻辑自行实现
        }
        return user;
    }

}
